/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gruposp2p.aularest.model.controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.gruposp2p.aularest.model.Itemcalificable;
import org.gruposp2p.aularest.model.Score;
import org.gruposp2p.aularest.model.Student;
import org.gruposp2p.aularest.model.controller.exceptions.NonexistentEntityException;
import org.gruposp2p.aularest.model.controller.exceptions.PreexistingEntityException;

/**
 *
 * @author jj
 */
public class ScoreJpaController {

    public ScoreJpaController() {
        emf = Persistence.createEntityManagerFactory("AulaRest_PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Score score) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Itemcalificable itemcalificableId = score.getItemcalificableId();
            if (itemcalificableId != null) {
                itemcalificableId = em.getReference(itemcalificableId.getClass(), itemcalificableId.getId());
                score.setItemcalificableId(itemcalificableId);
            }
            Student studentId = score.getStudentId();
            if (studentId != null) {
                studentId = em.getReference(studentId.getClass(), studentId.getId());
                score.setStudentId(studentId);
            }
            em.persist(score);
            if (itemcalificableId != null) {
                itemcalificableId.getScoreCollection().add(score);
                itemcalificableId = em.merge(itemcalificableId);
            }
            if (studentId != null) {
                studentId.getScoreCollection().add(score);
                studentId = em.merge(studentId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findScore(score.getId()) != null) {
                throw new PreexistingEntityException("Score " + score + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Score score) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Score persistentScore = em.find(Score.class, score.getId());
            Itemcalificable itemcalificableIdOld = persistentScore.getItemcalificableId();
            Itemcalificable itemcalificableIdNew = score.getItemcalificableId();
            Student studentIdOld = persistentScore.getStudentId();
            Student studentIdNew = score.getStudentId();
            if (itemcalificableIdNew != null) {
                itemcalificableIdNew = em.getReference(itemcalificableIdNew.getClass(), itemcalificableIdNew.getId());
                score.setItemcalificableId(itemcalificableIdNew);
            }
            if (studentIdNew != null) {
                studentIdNew = em.getReference(studentIdNew.getClass(), studentIdNew.getId());
                score.setStudentId(studentIdNew);
            }
            score = em.merge(score);
            if (itemcalificableIdOld != null && !itemcalificableIdOld.equals(itemcalificableIdNew)) {
                itemcalificableIdOld.getScoreCollection().remove(score);
                itemcalificableIdOld = em.merge(itemcalificableIdOld);
            }
            if (itemcalificableIdNew != null && !itemcalificableIdNew.equals(itemcalificableIdOld)) {
                itemcalificableIdNew.getScoreCollection().add(score);
                itemcalificableIdNew = em.merge(itemcalificableIdNew);
            }
            if (studentIdOld != null && !studentIdOld.equals(studentIdNew)) {
                studentIdOld.getScoreCollection().remove(score);
                studentIdOld = em.merge(studentIdOld);
            }
            if (studentIdNew != null && !studentIdNew.equals(studentIdOld)) {
                studentIdNew.getScoreCollection().add(score);
                studentIdNew = em.merge(studentIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = score.getId();
                if (findScore(id) == null) {
                    throw new NonexistentEntityException("The score with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Score score;
            try {
                score = em.getReference(Score.class, id);
                score.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The score with id " + id + " no longer exists.", enfe);
            }
            Itemcalificable itemcalificableId = score.getItemcalificableId();
            if (itemcalificableId != null) {
                itemcalificableId.getScoreCollection().remove(score);
                itemcalificableId = em.merge(itemcalificableId);
            }
            Student studentId = score.getStudentId();
            if (studentId != null) {
                studentId.getScoreCollection().remove(score);
                studentId = em.merge(studentId);
            }
            em.remove(score);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Score> findScoreEntities() {
        return findScoreEntities(true, -1, -1);
    }

    public List<Score> findScoreEntities(int maxResults, int firstResult) {
        return findScoreEntities(false, maxResults, firstResult);
    }

    private List<Score> findScoreEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Score as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Score findScore(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Score.class, id);
        } finally {
            em.close();
        }
    }

    public int getScoreCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Score as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
